﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CatEars.Core.Exceptions
{
    /// <summary>
    /// 组合异常(用于记录一系列的异常信息)
    /// </summary>
    public class MulitException : Exception
    {
        /// <summary>
        /// 发生过的异常
        /// </summary>
        LinkedList<Exception> m_innerExceptions;

        /// <summary>
        /// 发生过的异常
        /// </summary>
        public Exception[] InnerExceptions
        {
            get { return m_innerExceptions.ToArray(); }
        }

        /// <summary>
        /// 组合异常(用于记录一系列的异常信息)
        /// </summary>
        /// <param name="innerExc">异常信息</param>
        public MulitException(Exception innerExc = null) : base("组合异常消息", innerExc)
        {
            m_innerExceptions = new LinkedList<Exception>();
            if (innerExc != null)
            {
                m_innerExceptions.AddLast(innerExc);
            }
        }

        /// <summary>
        /// 追加异常
        /// </summary>
        /// <param name="exc"></param>
        public void Append(Exception exc)
        {
            m_innerExceptions.AddLast(exc);
        }

        /// <summary>
        /// 发生过的异常信息，重写Message
        /// </summary>
        public override string Message
        {
            get
            {
                if (m_innerExceptions != null && m_innerExceptions.Count == 1)
                {
                    return m_innerExceptions.First.Value.Message;
                }
                else
                {
                    return this.ToString();
                }
            }
        }

        /// <summary>
        /// 重写ToString
        /// </summary>
        /// <returns>ToString</returns>
        public override string ToString()
        {
            try
            {
                if (m_innerExceptions != null && m_innerExceptions.Count > 0)
                {
                    HashSet<string> hs = new HashSet<string>(
                        m_innerExceptions.Select(t => t.Message)
                        .Where(t => !string.IsNullOrEmpty(t)));
                    StringBuilder strB = new StringBuilder();
                    strB.Append("处理过程中出现以下错误：");
                    strB.Append(AppDefine.NewLine);
                    foreach (var item in hs)
                    {
                        strB.Append(item);
                        strB.Append(AppDefine.NewLine);
                    }
                    strB.Append("具体信息请查询InnerExceptions属性");
                    return strB.ToString();
                }
                else
                {
                    return base.ToString();
                }
            }
            catch
            {
                return base.ToString();
            }
        }
    }
}
